package awesome.server;

import java.util.logging.Logger;

import awesome.ServerConfig;
import awesome.request.RequestQueue;
import awesome.request.handler.RequestHandler;
import awesome.request.processor.RequestDelegator;
import awesome.site.loader.Synchronizer;
import awesome.site.proprietor.SiteProprietor;

/**
 * Holds the primary server components.
 * 
 * @author Chris Carpenter
 * 
 */
public class WebServer implements Server {
	
	//proprietor objects
	private SiteProprietor siteProprietor;
	private Synchronizer synchronizer;
	//request objects
	private RequestQueue requestQueue;
	private RequestHandler requestHandler;
	private RequestDelegator requestDelegator;
	//request handling threads
	private Thread requestHandlerThread;
	
	
	public WebServer() {
		//initialize proprietor objects
		this.siteProprietor = new SiteProprietor();
		this.synchronizer = new Synchronizer(this.siteProprietor,
				ServerConfig.INSTANCE.getProperty("site.root"));
		//initialize request objects
		this.requestQueue = new RequestQueue();
		this.requestHandler = new RequestHandler(this.requestQueue);
		this.requestDelegator = new RequestDelegator(this.requestQueue, this.siteProprietor);
		//initialize request handling threads
		this.requestHandlerThread = new Thread(requestHandler);
	}


	@Override
	public void startServer() {
		Logger.getLogger("awesome.server").info("Starting synchronizer.");
		synchronizer.startSynchronization();
		
		Logger.getLogger("awesome.server").info("Starting request processor.");
		requestDelegator.startDelegator();
		
		Logger.getLogger("awesome.server").info("Server request handler.");
		requestHandlerThread.start();
	}


	@Override
	public void stopServer() {
		Logger.getLogger("awesome.server").info("Stopping synchrnoizer.");
		synchronizer.stopSynchronization();
		
		Logger.getLogger("awesome.server").info("Stopping request handler.");
		requestHandlerThread.interrupt();
		
		Logger.getLogger("awesome.server").info("Stopping request processor.");
		requestDelegator.stopDelegator();
	}


	@Override
	public void restartServer() {
		stopServer();
		startServer();
	}
}
